package com.kreao.korean.repository;

import com.kreao.korean.entity.Word;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface WordRepository extends JpaRepository<Word, Long> {
    
    Page<Word> findByUserIdAndKoreanContainingOrChineseContaining(
        Long userId, String korean, String chinese, Pageable pageable);
    
    Page<Word> findByUserId(Long userId, Pageable pageable);
    
    Page<Word> findByUserIdAndCategory(Long userId, Word.WordCategory category, Pageable pageable);
    
    Page<Word> findByUserIdAndLevel(Long userId, Word.WordLevel level, Pageable pageable);
    
    Page<Word> findByUserIdAndIsFavorite(Long userId, Boolean isFavorite, Pageable pageable);
    
    List<Word> findByUserIdAndNextReviewTimeBefore(Long userId, LocalDateTime time);
    
    @Query("SELECT w FROM Word w WHERE w.user.id = :userId AND w.accuracy < :accuracy ORDER BY w.accuracy ASC")
    List<Word> findWordsNeedReview(@Param("userId") Long userId, @Param("accuracy") Double accuracy);
    
    @Query("SELECT w FROM Word w WHERE w.isPublic = true AND (w.korean LIKE %:keyword% OR w.chinese LIKE %:keyword%)")
    Page<Word> findPublicWordsByKeyword(@Param("keyword") String keyword, Pageable pageable);
    
    @Query("SELECT w FROM Word w WHERE w.isPublic = true AND w.category = :category")
    Page<Word> findPublicWordsByCategory(@Param("category") Word.WordCategory category, Pageable pageable);
    
    @Query("SELECT COUNT(w) FROM Word w WHERE w.user.id = :userId")
    Long countByUserId(@Param("userId") Long userId);
    
    @Query("SELECT AVG(w.accuracy) FROM Word w WHERE w.user.id = :userId")
    Double getAverageAccuracyByUserId(@Param("userId") Long userId);
    
    @Query("SELECT COUNT(w) FROM Word w WHERE w.user.id = :userId AND w.createdAt >= :startDate")
    Long countByUserIdAndCreatedAtAfter(@Param("userId") Long userId, @Param("startDate") LocalDateTime startDate);
    
    @Query("SELECT SUM(w.reviewCount) FROM Word w WHERE w.user.id = :userId")
    Long getTotalReviewCountByUserId(@Param("userId") Long userId);
} 